import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;

import com.formdev.flatlaf.FlatLightLaf;
import project.*;
public class Frame extends JFrame {

    TabItem tabItem;
    public Frame(String title) {
        super(title);
        Container container = getContentPane();
//        container.setLayout(new BorderLayout());
//        try {
//            UIManager.setLookAndFeel( new FlatLightLaf() );
//        } catch( Exception ex ) {
//            System.err.println( "Failed to initialize LaF" );
//        }
        //初始化
        Operation.addPath(Element.openFile);
        tabItem = new TabItem("新文件.txt",null,Operation.setIcon("txt"),"txt");
        container.add(Element.mainJTP);
        Element.textList.add(tabItem.getTextArea());
        Element.titleList.add(tabItem.getLabelText());
        Element.jfc = Operation.initJFileChooser(Element.jfc);

        //设置菜单属性
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
        this.setJMenuBar(Element.menuBar);
        Operation.initMenu();

        Element.jfc.addChoosableFileFilter(Element.txtFilter);
        Element.jfc.addChoosableFileFilter(Element.mdFilter);

        /**
         * 打开官网
         * **/
        Element.thisJML.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Desktop desktop = Desktop.getDesktop();
                try {
                    URI uri = new URI("https://wd_moonmoonbird.gitee.io/easypad");
                    desktop.browse(uri);

                } catch (URISyntaxException | IOException ex) {
                    ex.printStackTrace();
                }
            }
        });

//        String[][] fileNames = {
//                { ".txt", "文本文件(*.txt)" },
//                { ".md", "MarkDown文件(*.md)" },
//        };
//        for(final String[] fileEName:fileNames) {
//            Element.jfc.setFileFilter(new FileFilter() {
//                @Override
//                public boolean accept(File file) {
//                    if (file.getName().endsWith(fileEName[0]) || file.isDirectory()) {
//                        return true;
//                    }
//                    return false;
//                }
//
//                @Override
//                public String getDescription() {
//                    return fileEName[1];
//                }
//            });
//        }



//        /**
//         * 设置JFileChooser的过滤器
//         * **/
//        Element.jfc.setFileFilter(new FileFilter() {
//            @Override
//            public boolean accept(File f) {
//                if (f.isDirectory()) {
//                    return true;
//                }
//                return f.getName().endsWith(".txt");
//            }
//
//            @Override
//            public String getDescription() {
//                return ".txt";
//            }
//        });


        /**
         * 全选菜单事件
         * **/
        Element.selectAllJML.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Element.textList.get(Element.mainJTP.getSelectedIndex()).selectAll();
            }
        });

        /**
         * 复制菜单事件
         * **/
        Element.copyJML.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Element.textList.get(Element.mainJTP.getSelectedIndex()).copy();
            }
        });

        /**
         * 粘贴菜单事件
         * **/
        Element.pasteJML.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Element.textList.get(Element.mainJTP.getSelectedIndex()).paste();
            }
        });

        /**
         * 剪切菜单事件
         * **/
        Element.cutJML.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Element.textList.get(Element.mainJTP.getSelectedIndex()).cut();
            }
        });

        /**
         * 删除菜单事件
         * **/
        Element.deleteJML.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Element.textList.get(Element.mainJTP.getSelectedIndex()).replaceSelection("");
            }
        });

//        Element.lightJML.addActionListener(new AbstractAction() {
//            @Override
//            public void actionPerformed(ActionEvent e) {
//                if (Element.lightJML.getText().equals("明亮主题")) {
//                    JOptionPane.showMessageDialog(null, "新主题将在下次启动后生效", "提示",JOptionPane.WARNING_MESSAGE);
//                }
//                Operation.setLightDarkTheme("FlatLightLaf");
//            }
//        });


        Element.undoJML.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    TabTextArea.um.undo();
                }catch (Exception e1) {
                    return;
                }
            }
        });

        Element.redoJML.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    TabTextArea.um.redo();
                }catch (Exception e1) {
                    return;
                }
            }
        });

        /**
         * 测试遍历
         * **/
        Element.printList.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < Element.pathList.size(); i++) {
                    System.out.println(Element.pathList.get(i));
                }
            }
        });


        /**
         * 新建markDown菜单被激活
         * **/
        Element.markDownJMI.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String title = JOptionPane.showInputDialog(null, "请输入文件名:\n", "新建文件", JOptionPane.PLAIN_MESSAGE);
                if (title == null) return;

                Element.tabIndex++;
                title = title.indexOf("md") < 0 ? title += ".md" : title;
                Element.pathList.add(null);
                tabItem = new TabItem(title,null,Operation.setIcon(".md"),"md");
                Element.titleList.add(tabItem.getLabelText());
                Element.textList.add(tabItem.getTextArea());
            }
        });


        /**
         * 新建txt文档菜单被激活
         * **/
        Element.txtJMI.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String title = JOptionPane.showInputDialog(null, "请输入文件名:\n", "新建文件", JOptionPane.PLAIN_MESSAGE);
                if (title == null) return;

                Element.tabIndex++;
                title = title.indexOf(".txt") < 0 ? title += ".txt" : title;
                Element.pathList.add(null);
                tabItem = new TabItem(title,null,Operation.setIcon("txt"),"txt");
                Element.textList.add(tabItem.getTextArea());
                Element.titleList.add(tabItem.getLabelText());
            }
        });





        /**
         * 打开菜单项被激活
         * **/
        Element.openJMI.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //弹出读取文件对话框
                Element.jfc.setDialogType(JFileChooser.OPEN_DIALOG);
                int result = Element.jfc.showOpenDialog(Element.jfc);
                if (result == JFileChooser.APPROVE_OPTION) {
                    //读取文件
                    if ((Element.openFile = Element.jfc.getSelectedFile()) == null) return;
                    String path = Element.openFile.getPath();

                    //将文件名显示到选择夹子项，将文件内容显示到文本框中
                    String fileName = Operation.getFileName(path);
                    String type = Operation.getFileType(fileName);
                    Operation.addPath(Element.openFile);
                    tabItem = new TabItem(fileName,null,Operation.setIcon(type),type);
                    tabItem.textArea.setText(Operation.readFile(path));
                    Element.textList.add(tabItem.getTextArea());
                    Element.titleList.add(tabItem.getLabelText());
                }
            }
        });


        /**
         * 为选项卡添加侦听事件
         * **/
        Element.mainJTP.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                Element.nowTabSelect = Element.mainJTP.getSelectedIndex();
            }
        });

        /**
         * 另存为菜单项被激活
         * **/
        Element.saveOtherJMI.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Operation.saveFile();
            }
        });

        /**
         * 保存菜单项被激活
         * **/
        Element.saveJMI.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int index = Element.mainJTP.getSelectedIndex();
                if (Element.pathList.get(index) == null) {
                    Operation.saveFile();
                } else {
                    try {
                        FileWriter writer = new FileWriter(Element.pathList.get(index));
                        writer.append(Element.textList.get(index).getText());
                        writer.flush();
                        writer.close();
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }
                        Operation.titleStart();
                }
            }
        });
    }
}
